/*
 * Copyright (c) 2023 fred
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import { Document } from '../../nodes/Document'
import { Element } from '../../nodes/Element'
import { Evaluator } from '../Evaluator'
export abstract class EvaluatorCssNthEvaluator extends Evaluator {
  readonly a: number
  readonly b: number

  constructor(b: number, a: number = 0) {
    super()
    this.a = a
    this.b = b
  }

  public matches(root: Element, element: Element): boolean {
    let p = element.parent()
    if (p === undefined || p === null || (p instanceof Document)) {
      return false
    }
    let pos = this.calculatePosition(root, element)
    if (this.a === 0) {
      return pos === this.b
    }
    return (pos - this.b) * this.a >= 0 && (pos - this.b) % this.a === 0
  }

  public toString(): string {
    if (this.a === 0) {
      return `:${this.getPseudoClass()}(${this.b})`
    }
    if (this.b === 0) {
      return `:${this.getPseudoClass()}(${this.a})`
    }
    return `:${this.getPseudoClass()}(${this.a}${this.b})`
  }

  abstract getPseudoClass(): string

  abstract calculatePosition(root: Element, element: Element): number
}